import { useTransition, useState } from "react";
import { List, Input, Flex } from "antd";
interface Item {
  id: number;
  name: string;
  address: string;
}
export default function Demo04() {
  const [isPending, startTransition] = useTransition();
  const [keyWord, setKeyWord] = useState("");
  const [list, setList] = useState<Item[]>([]);
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setKeyWord(value);
    
    // 模拟网络请求
    // 使用 startTransition 来标记这个更新为过渡更新，input输入时相对流畅 (但我实际测试：在不降cpu性能情况下， 不管用不用startTransition，效果感觉差不多)
    startTransition(async () => {
      const response = await fetch(`/api/list?keyWord=${value}`)
      const data = await response.json()
      startTransition(() => {
        setList(data.list);
      })
    })

    // 不使用 startTransition, 直接更新, input输入时会有卡顿
    // const fn = async () => {
    //   const response = await fetch(`/api/list?keyWord=${value}`)
    //   const data = await response.json()
    //   setList(data.list)
    // }
    // fn()
  };
  return (
    <>
      <h1>useTransition示例</h1>
      <p style={{ color: "#c33434" }}>注意：useTransition 必须是同步的</p>
      <Flex>
        <Input placeholder="请输入关键字" value={keyWord} onChange={handleInputChange} />
      </Flex>
      <List
        loading={isPending}
        dataSource={list}
        renderItem={(item) => (
          <List.Item key={item.id}>
            <List.Item.Meta title={item.name} description={item.address} />
          </List.Item>
        )}
      />
    </>
  );
}
